package net.joyphper.ctrl.security;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.joyphper.commons.security.SecurityUtil;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.code.kaptcha.Producer;

@Controller("net.joyphper.ctrl.security.VerifyCodeCtrl")
@RequestMapping(value = "/security/captcha.htm", method = RequestMethod.GET)
public class CaptchaCtrl {
	@Autowired
	private SecurityUtil securityUtil;
	
	@Autowired
	private Producer captchaProducer;
	
	private static final Logger logger = Logger.getLogger(CaptchaCtrl.class);

	@RequestMapping
	public void generate(HttpServletResponse response) throws IOException {
		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/png");
		
		String sRand = captchaProducer.createText();
		// 将认证码存入到缓存
		this.securityUtil.setCaptcha(sRand);
				
		BufferedImage bi = captchaProducer.createImage(sRand);
		
		ServletOutputStream out = null;
		try {
			out = response.getOutputStream();
			ImageIO.write(bi, "png", out);
			out.flush();
		}catch(Exception e){
			logger.error("生成验证码失败：",e);
		}finally {
			out.close();
		}
	}
}
